import { useMount } from "ahooks"
import { useData } from "magic-ui-react"
import { useState } from "react"

export const useAppHover = (ref: React.MutableRefObject<any>) => {
  const [hover, setHover] = useState(false)
  useMount(() => {
    ref.current.onmouseenter = () => {
      setHover(true)
    }
    ref.current.onmouseleave = () => {
      setHover(false)
    }
  })
  return hover
}

export const useClickType = <T extends HTMLElement = any,>(
  ref: React.RefObject<T> | null,
  options?: {
    callback?: (clickType: 'doubleClick' | 'longPress') => void
    /**
     * 定义双击和长按的有效时间
     */
    time?: {
      doubleClick: number
      longPress: number
    },
    /**
     * 长按触发模式
     * @defatult byTime 默认根据时间自动触发
     * @params mouseUp 根据鼠标抬起时间触发
     */
    longPressTriggerType?: 'mouseUp' | 'byTime'
  },
) => {

  const newOptions = {
    longPressTriggerType: 'byTime',
    ...options
  }

  const time = {
    doubleClick: 200,
    longPress: 700,
    ...options?.time
  }
  const [clickType, setClickType] = useState<'doubleClick' | 'longPress'>()

  const data = useData<{
    setTimeoutId?: NodeJS.Timer,
    mouseDownTime: number,
  }>({
    mouseDownTime: 0,
  })

  useMount(() => {
    if (ref?.current) {
      ref.current.onmousedown = (event) => {
        const prevMouseDownTime = data.mouseDownTime
        data.mouseDownTime = event.timeStamp

        if (newOptions.longPressTriggerType === 'byTime') {
          data.setTimeoutId = setTimeout(() => {
            options?.callback?.('longPress')
            setClickType('longPress')
          }, time.longPress)
        }
        if (
          data.mouseDownTime !== 0 &&
          (data.mouseDownTime - prevMouseDownTime < time.doubleClick)
        ) {
          options?.callback?.('doubleClick')
          setClickType('doubleClick')
        }
      }
      ref.current.onmouseup = (event) => {
        if (
          (event.timeStamp - data.mouseDownTime > time.longPress) &&
          newOptions.longPressTriggerType === 'mouseUp'
        ) {
          options?.callback?.('longPress')
          setClickType('longPress')
        }
        if (newOptions.longPressTriggerType === 'byTime') {
          clearTimeout(data.setTimeoutId)
        }
      }
    }
  })

  return clickType
}
